package com.example.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
	ImageView image;
	Button btn_start,btn_stop;
	int imgstart = 0;  
	int images[] = new int[]{
			R.drawable.a,
			R.drawable.b,
			R.drawable.c,
			R.drawable.d};
	boolean flag= true;
	Handler handler = new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what) {
			case 1:
				 if(imgstart>=3)
					 imgstart = 0;
				 image.setImageResource(images[imgstart++]);  
				break;

			default:
				break;
			}
		}
	};
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.imageView1);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        
        btn_start.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startCount();
			}
		});
        
        btn_stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				stopCount();
			}
		});
        
    }
    
	protected void stopCount() {
		// TODO Auto-generated method stub
		flag = false;
	}

	private void startCount() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				flag = true;
				while(flag){
					try {
						Thread.sleep(200);
						handler.sendEmptyMessage(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
